package cn.zxf.note.note.note;

import cn.zxf.note.common.exception.BizException;
import cn.zxf.note.note.parse.NoteVo;
import cn.zxf.note.note.review.NoteReviewSupport;
import cn.zxf.note.note.type.NoteType;
import cn.zxf.note.note.type.NoteTypeSupport;
import com.github.zengxf.common.utils.DateUtils;
import com.github.zengxf.common.utils.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

/**
 * Created by zengxf on 2019/4/2.
 */
@Slf4j
@Component
public class NoteSupport {

    @Autowired
    private NoteRepository repos;
    @Autowired
    private NoteDao dao;
    @Autowired
    private NoteTypeSupport typeSupport;
    @Autowired
    private NoteReviewSupport reviewSupport;

    public int countByTypeId(Integer typeId) {
        return repos.countByTypeId(typeId);
    }

    public void saveForImport(Integer userId, String month, String day, NoteVo vo) {
        LocalDate date = LocalDate.parse(month + "-" + day);
        this.saveForImport(userId, date, vo);
    }

    public void saveForImport(Integer userId, String day, NoteVo vo) {
        LocalDate date = LocalDate.now().withDayOfMonth(Integer.parseInt(day));
        this.saveForImport(userId, date, vo);
    }

    public void saveForImport(Integer userId, LocalDate date, NoteVo vo) {
        Note note = dao.findByDayAndTitle(userId, date, vo.getTitle());
        boolean insert = false;
        if (note == null) {
            note = new Note();
            insert = true;
        }
        if (!insert) {
            log.warn("userId: [{}], date: [{}], title: [{}] 已存在", userId, date, vo.getTitle());
        }
        String typeName = vo.getType();
        NoteType type = typeSupport.findOrSave(userId, typeName);
        note.setUserId(userId)
                .setTypeId(type.getId())
                .setStatus(NoteStatusEnum.NORMAL.code)
                .setTitle(vo.getTitle())
                .setContentType(NoteContentTypeEnum.MACKDOWN.code)
                .setContent(ListUtils.join(vo.getContent()))
                .setCreateDate(DateUtils.toDate(date));
        repos.save(note);
        if (insert)
            reviewSupport.batchInsertForImport(date, userId, note.getId());
    }

    public Note validateAndGet(Integer noteId) {
        if (noteId == null)
            throw BizException.of("笔记 ID 为空");
        return repos.findById(noteId)
                .orElseThrow(() -> BizException.of("笔记不存在"));
    }

}
